<template>
	<div class="combined-chart-wrapper">
		<!-- 左右分布布局 -->
		<div v-if="showSplitLayout" class="split-layout">
			<!-- 左侧：开工情况 -->
			<div class="chart-half left-chart">
				<div class="chart-title">开工情况</div>
				<div ref="startChartRef" class="chart-container"></div>
			</div>
			<!-- 右侧：完工情况 -->
			<div class="chart-half right-chart">
				<div class="chart-title">完工情况</div>
				<div ref="endChartRef" class="chart-container"></div>
			</div>
		</div>
		<!-- 原有的合并布局 -->
		<div v-else class="single-layout">
			<div ref="chartRef" class="combined-chart-container">
				<!-- 保持原有的空间给ECharts内置图例使用 -->
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import * as echarts from 'echarts';

// 导入数据类型
interface DailyPoint {
	date: string;
	planStart: number;
	planEnd: number;
	actualStart: number;
	actualEnd: number;
}

interface Props {
	chartData: DailyPoint[];
	areaName: string;
	showTimeProgress?: boolean; // 是否显示时间进度线
	showSplitLayout?: boolean; // 是否使用左右分布布局
	chartType?: 'start' | 'end' | 'both'; // 图表类型：开工、完工或全部
}

const props = withDefaults(defineProps<Props>(), {
	showTimeProgress: true,
	showSplitLayout: false,
	chartType: 'both',
});

const chartRef = ref<HTMLElement>();
const startChartRef = ref<HTMLElement>();
const endChartRef = ref<HTMLElement>();
let chart: echarts.ECharts | null = null;
let startChart: echarts.ECharts | null = null;
let endChart: echarts.ECharts | null = null;

// 等待容器宽高>0
function waitForDOMReady(el: HTMLElement, maxWait = 2000): Promise<boolean> {
	return new Promise((resolve) => {
		const startTime = Date.now();
		const check = () => {
			if (el && el.offsetWidth > 0 && el.offsetHeight > 0) {
				resolve(true);
				return;
			}
			if (Date.now() - startTime > maxWait) {
				resolve(false);
				return;
			}
			setTimeout(check, 50);
		};
		check();
	});
}

function renderChart(option: any) {
	// 增强的图表渲染函数，添加更多安全检查
	if (!chartRef.value) {
		console.warn('Chart container ref is not available');
		return;
	}

	// 确保容器有尺寸
	if (chartRef.value.offsetWidth === 0 || chartRef.value.offsetHeight === 0) {
		console.warn('Chart container has zero dimensions, retrying...', {
			width: chartRef.value.offsetWidth,
			height: chartRef.value.offsetHeight,
		});
		// 延迟重试
		setTimeout(() => renderChart(option), 100);
		return;
	}

	try {
		if (!chart && chartRef.value) {
			chart = echarts.init(chartRef.value);

			// 添加图表事件监听器以捕获错误
			chart.on('error', function (params) {
				console.error('ECharts rendering error:', params);
			});

			// 添加鼠标事件错误处理
			chart.on('mousemove', function (params) {
				try {
					// 安全处理鼠标移动事件，避免GlobalModel错误
				} catch (error) {
					console.warn('Chart mousemove error:', error);
				}
			});
		}

		if (!chart) {
			console.error('Failed to initialize chart instance');
			return;
		}

		// 验证option结构
		if (!option || !option.series || !Array.isArray(option.series) || option.series.length === 0) {
			console.error('Invalid chart option structure:', option);
			return;
		}

		// 验证series中是否有有效数据
		const hasValidSeries = option.series.some((series) => series && series.data && Array.isArray(series.data) && series.data.length > 0);

		if (!hasValidSeries) {
			console.warn('No valid series data found, skipping render');
			return;
		}

		// 验证xAxis是否存在
		if (!option.xAxis || !option.xAxis.data || !Array.isArray(option.xAxis.data) || option.xAxis.data.length === 0) {
			console.error('Invalid xAxis configuration:', option.xAxis);
			return;
		}

		chart.setOption(option, true);

		// 延迟resize确保图表正确渲染，避免主进程中调用
		nextTick(() => {
			setTimeout(() => {
				if (chart && !chart.isDisposed()) {
					try {
						chart.resize();
					} catch (error) {
						console.warn('Chart resize failed:', error);
					}
				}
			}, 150);
		});
	} catch (error) {
		console.error('Error in renderChart function:', error);
	}
}

const renderSplitCharts = async () => {
	if (!props.chartData || props.chartData.length === 0) {
		console.warn('没有图表数据，跳过渲染', props.chartData);
		return;
	}

	console.log('开始渲染分离图表', {
		dataLength: props.chartData.length,
		areaName: props.areaName,
		firstItem: props.chartData[0],
	});

	// 等待DOM准备好
	await nextTick();
	if (startChartRef.value) {
		const isReady = await waitForDOMReady(startChartRef.value);
		if (!isReady) return;
	}
	if (endChartRef.value) {
		const isReady = await waitForDOMReady(endChartRef.value);
		if (!isReady) return;
	}

	// 获取今天的日期
	const today = new Date();
	const todayStr = today.toISOString().slice(0, 10);

	// 过滤数据：实际数据只显示到今天的数据
	const filteredData = props.chartData.map((item) => {
		const isTodayOrBefore = item.date <= todayStr;
		return {
			...item,
			actualStart: isTodayOrBefore ? item.actualStart : null,
			actualEnd: isTodayOrBefore ? item.actualEnd : null,
			planStart: item.planStart,
			planEnd: item.planEnd,
		};
	});

	// 格式化日期为 MM-DD
	const dates = filteredData.map((item) => {
		const date = new Date(item.date);
		const mm = String(date.getMonth() + 1).padStart(2, '0');
		const dd = String(date.getDate()).padStart(2, '0');
		return `${mm}-${dd}`;
	});

	// 渲染开工图表
	setTimeout(() => {
		renderStartChart(dates, filteredData);
	}, 50);
	// 渲染完工图表
	setTimeout(() => {
		renderEndChart(dates, filteredData);
	}, 100);
};

const renderStartChart = (dates: string[], filteredData: any[]) => {
	if (!startChartRef.value || !dates || dates.length === 0) return;

	// 确保容器有尺寸
	if (startChartRef.value.offsetWidth === 0 || startChartRef.value.offsetHeight === 0) {
		console.warn('开工图表容器尺寸为0，跳过渲染');
		return;
	}

	try {
		if (startChart) {
			startChart.dispose();
			startChart = null;
		}
		startChart = echarts.init(startChartRef.value);

		// 添加错误处理
		startChart.on('error', function (params) {
			console.error('Start chart error:', params);
		});

		startChart.on('mousemove', function (params) {
			try {
				// 安全处理鼠标移动事件
			} catch (error) {
				console.warn('Start chart mousemove error:', error);
			}
		});
	} catch (error) {
		console.error('初始化开工图表失败:', error);
		return;
	}

	const planStartData = filteredData.map((item) => item.planStart || 0);
	const actualStartData = filteredData.map((item) => item.actualStart);

	const option = {
		title: {
			text: `${props.areaName} - 开工情况`,
			left: 'center',
			textStyle: { fontSize: 14, fontWeight: 'bold', color: '#303133' },
		},
		tooltip: {
			show: true,
			trigger: 'axis',
			triggerOn: 'mousemove|click',
			confine: true,
			appendToBody: true,
			axisPointer: {
				type: 'cross',
				animation: true,
			},
			formatter: function (params: any[]) {
				// 安全检查：确保params存在且不为空
				if (!params || params.length === 0) {
					return '暂无数据';
				}

				// 安全获取坐标轴值
				const axisValue = params[0]?.axisValue || params[0]?.name || '未知日期';
				let tooltipText = `<strong>${axisValue}</strong><br/>`;

				params.forEach((param) => {
					// 安全获取参数值
					const seriesName = param.seriesName || '未知系列';
					const marker = param.marker || '●';
					// 显示所有数据，null/undefined显示为'-'，0显示为'0'
					let value;
					if (param.value === null || param.value === undefined) {
						value = '-';
					} else if (param.value === 0) {
						value = '0';
					} else {
						value = param.value.toString();
					}
					tooltipText += `${marker}${seriesName}: ${value}<br/>`;
				});
				return tooltipText;
			},
		},
		legend: { bottom: 5, data: ['计划开工', '实际开工'], textStyle: { fontSize: 12 } },
		grid: { left: '3%', right: '4%', bottom: '15%', top: '10%', containLabel: true },
		xAxis: { type: 'category', data: dates, axisLabel: { fontSize: 10, rotate: 45 } },
		yAxis: { type: 'value', axisLabel: { fontSize: 10 } },
		series: [
			{
				name: '计划开工',
				type: 'bar',
				data: planStartData,
				itemStyle: { color: '#409EFF' },
				barWidth: '60%',
				label: { show: true, position: 'top', fontSize: 10, color: '#333', fontWeight: 'bold' },
			},
			{
				name: '实际开工',
				type: 'line',
				data: actualStartData,
				itemStyle: { color: '#67C23A' },
				lineStyle: { width: 2 },
				symbol: 'circle',
				symbolSize: 4,
				smooth: false,
				connectNulls: false,
			},
		],
	};

	try {
		startChart.setOption(option, true);
		// 触发resize，确保图表正确显示
		nextTick(() => {
			setTimeout(() => {
				if (startChart) {
					startChart.resize();
				}
			}, 100);
		});
	} catch (error) {
		console.error('设置开工图表选项失败:', error);
	}
};

const renderEndChart = (dates: string[], filteredData: any[]) => {
	if (!endChartRef.value || !dates || dates.length === 0) return;

	// 确保容器有尺寸
	if (endChartRef.value.offsetWidth === 0 || endChartRef.value.offsetHeight === 0) {
		console.warn('完工图表容器尺寸为0，跳过渲染');
		return;
	}

	try {
		if (endChart) {
			endChart.dispose();
			endChart = null;
		}
		endChart = echarts.init(endChartRef.value);

		// 添加错误处理
		endChart.on('error', function (params) {
			console.error('End chart error:', params);
		});

		endChart.on('mousemove', function (params) {
			try {
				// 安全处理鼠标移动事件
			} catch (error) {
				console.warn('End chart mousemove error:', error);
			}
		});
	} catch (error) {
		console.error('初始化完工图表失败:', error);
		return;
	}

	const planEndData = filteredData.map((item) => item.planEnd || 0);
	const actualEndData = filteredData.map((item) => item.actualEnd);

	const option = {
		title: {
			text: `${props.areaName} - 完工情况`,
			left: 'center',
			textStyle: { fontSize: 14, fontWeight: 'bold', color: '#303133' },
		},
		tooltip: {
			show: true,
			trigger: 'axis',
			triggerOn: 'mousemove|click',
			confine: true,
			appendToBody: true,
			axisPointer: {
				type: 'cross',
				animation: true,
			},
			formatter: function (params: any[]) {
				// 安全检查：确保params存在且不为空
				if (!params || params.length === 0) {
					return '暂无数据';
				}

				// 安全获取坐标轴值
				const axisValue = params[0]?.axisValue || params[0]?.name || '未知日期';
				let tooltipText = `<strong>${axisValue}</strong><br/>`;

				params.forEach((param) => {
					// 安全获取参数值
					const seriesName = param.seriesName || '未知系列';
					const marker = param.marker || '●';
					// 显示所有数据，null/undefined显示为'-'，0显示为'0'
					let value;
					if (param.value === null || param.value === undefined) {
						value = '-';
					} else if (param.value === 0) {
						value = '0';
					} else {
						value = param.value.toString();
					}
					tooltipText += `${marker}${seriesName}: ${value}<br/>`;
				});
				return tooltipText;
			},
		},
		legend: { bottom: 5, data: ['计划完工', '实际完工'], textStyle: { fontSize: 12 } },
		grid: { left: '3%', right: '4%', bottom: '15%', top: '10%', containLabel: true },
		xAxis: { type: 'category', data: dates, axisLabel: { fontSize: 10, rotate: 45 } },
		yAxis: { type: 'value', axisLabel: { fontSize: 10 } },
		series: [
			{
				name: '计划完工',
				type: 'bar',
				data: planEndData,
				itemStyle: { color: '#E6A23C' },
				barWidth: '60%',
				label: { show: true, position: 'top', fontSize: 10, color: '#333', fontWeight: 'bold' },
			},
			{
				name: '实际完工',
				type: 'line',
				data: actualEndData,
				itemStyle: { color: '#F56C6C' },
				lineStyle: { width: 2 },
				symbol: 'diamond',
				symbolSize: 4,
				smooth: false,
				connectNulls: false,
			},
		],
	};

	try {
		endChart.setOption(option, true);
		// 触发resize，确保图表正确显示
		nextTick(() => {
			setTimeout(() => {
				if (endChart) {
					endChart.resize();
				}
			}, 100);
		});
	} catch (error) {
		console.error('设置完工图表选项失败:', error);
	}
};

const option = async () => {
	console.log('CombinedAreaChart option函数被调用', {
		chartData: props.chartData,
		dataLength: props.chartData?.length || 0,
		areaName: props.areaName,
		showSplitLayout: props.showSplitLayout,
		chartType: props.chartType,
		showTimeProgress: props.showTimeProgress,
	});

	// 增强的数据验证 - 确保数据结构正确
	if (!props.chartData || props.chartData.length === 0) {
		console.warn('CombinedAreaChart数据为空，跳过渲染');
		// 清理现有图表实例，避免残留错误
		if (chart) {
			try {
				chart.dispose();
				chart = null;
			} catch (error) {
				console.warn('清理图表实例失败:', error);
			}
		}
		if (startChart) {
			try {
				startChart.dispose();
				startChart = null;
			} catch (error) {
				console.warn('清理开工图表实例失败:', error);
			}
		}
		if (endChart) {
			try {
				endChart.dispose();
				endChart = null;
			} catch (error) {
				console.warn('清理完工图表实例失败:', error);
			}
		}
		return;
	}

	// 验证数据结构的有效性
	const hasValidData = props.chartData.some(
		(item) =>
			item && typeof item.date === 'string' && (typeof item.planStart === 'number' || typeof item.actualStart === 'number' || typeof item.planEnd === 'number' || typeof item.actualEnd === 'number')
	);

	if (!hasValidData) {
		console.warn('CombinedAreaChart数据结构无效，跳过渲染:', props.chartData);
		return;
	}

	// 如果使用分布布局，调用分离渲染函数
	if (props.showSplitLayout) {
		// 清理合并显示的图表
		if (chart) {
			chart.dispose();
			chart = null;
		}
		await renderSplitCharts();
		return;
	}

	// 如果使用合并显示，清理分离显示的图表
	if (startChart) {
		startChart.dispose();
		startChart = null;
	}
	if (endChart) {
		endChart.dispose();
		endChart = null;
	}

	// 原有的合并显示逻辑
	// 获取今天的日期
	const today = new Date();
	const todayStr = today.toISOString().slice(0, 10);

	// 过滤数据：实际数据只显示到今天的数据
	const filteredData = props.chartData.map((item) => {
		const isTodayOrBefore = item.date <= todayStr;
		return {
			...item,
			// 实际数据只显示到今天的值，今日之后设为null让折线断开
			actualStart: isTodayOrBefore ? item.actualStart : null,
			actualEnd: isTodayOrBefore ? item.actualEnd : null,
			// 计划数据保持原样
			planStart: item.planStart,
			planEnd: item.planEnd,
		};
	});

	// 格式化日期为 MM-DD
	const dates = filteredData.map((item) => {
		const date = new Date(item.date);
		const mm = String(date.getMonth() + 1).padStart(2, '0');
		const dd = String(date.getDate()).padStart(2, '0');
		return `${mm}-${dd}`;
	});

	const planEndData = filteredData.map((item) => item.planEnd || 0);
	// 实际完工数据截止到今天，今天之后为null
	const actualEndData = filteredData.map((item) => item.actualEnd);

	// 计算时间线数据：从第一天的0开始，到最后一天计划完工的值，形成斜线
	const finalPlanEnd = planEndData[planEndData.length - 1] || 0;
	const timelineData = filteredData.map((item, index) => {
		// 线性递增：从0到最终计划完工数
		// 确保第一天是0，最后一天是finalPlanEnd
		if (filteredData.length === 1) {
			return finalPlanEnd; // 只有一天的情况
		}
		return (index / (filteredData.length - 1)) * finalPlanEnd;
	});

	// 等待DOM容器准备就绪
	await nextTick();
	if (!chartRef.value) {
		console.error('Chart container ref not found');
		return;
	}

	// 等待容器有尺寸
	const isReady = await waitForDOMReady(chartRef.value);
	if (!isReady) {
		console.error('Chart container not ready after waiting');
		return;
	}

	try {
		if (chart) {
			chart.dispose();
			chart = null;
		}

		chart = echarts.init(chartRef.value);

		// 添加错误处理
		chart.on('error', function (params) {
			console.error('ECharts error in combined chart:', params);
		});
	} catch (error) {
		console.error('Failed to initialize combined chart:', error);
		return;
	}

	// 根据chartType决定显示的数据和系列
	let series: any[] = [];
	let titleText = '';
	let legendData: string[] = [];

	if (props.chartType === 'start') {
		// 开工情况：计划开工柱状 + 实际开工线性
		const planStartData = filteredData.map((item) => item.planStart || 0);
		const actualStartData = filteredData.map((item) => item.actualStart);

		series = [
			// 计划开工 - 柱状图
			{
				name: '计划开工',
				type: 'bar',
				data: planStartData,
				itemStyle: { color: '#409EFF' },
				barWidth: '60%',
				tooltip: {
					show: true,
				},
				label: {
					show: true,
					position: 'top',
					fontSize: 10,
					color: '#333',
					fontWeight: 'bold',
					formatter: function (params: any) {
						return params.value === 0 ? '0' : params.value || '';
					},
				},
			},
			// 实际开工 - 折线图
			{
				name: '实际开工',
				type: 'line',
				data: actualStartData,
				itemStyle: { color: '#67C23A' },
				lineStyle: { width: 3 },
				symbol: 'circle',
				symbolSize: 6,
				smooth: false,
				connectNulls: false,
				tooltip: {
					show: true,
				},
			},
		];

		titleText = `${props.areaName} - 开工情况`;
		legendData = ['计划开工', '实际开工'];
	} else if (props.chartType === 'end') {
		// 完工情况：计划完工柱状 + 实际完工线性
		series = [
			// 计划完工 - 柱状图
			{
				name: '计划完工',
				type: 'bar',
				data: planEndData,
				itemStyle: { color: '#E6A23C' },
				barWidth: '60%',
				tooltip: {
					show: true,
				},
				label: {
					show: true,
					position: 'top',
					fontSize: 10,
					color: '#333',
					fontWeight: 'bold',
					formatter: function (params: any) {
						return params.value === 0 ? '0' : params.value || '';
					},
				},
			},
			// 实际完工 - 折线图
			{
				name: '实际完工',
				type: 'line',
				data: actualEndData,
				itemStyle: { color: '#F56C6C' },
				lineStyle: { width: 3 },
				symbol: 'circle',
				symbolSize: 6,
				smooth: false,
				connectNulls: false,
				tooltip: {
					show: true,
				},
			},
		];

		titleText = `${props.areaName} - 完工情况`;
		legendData = ['计划完工', '实际完工'];
	} else {
		// 原有的完工情况分析（保持不变）
		series = [
			// 计划完工 - 柱状图
			{
				name: '计划完工',
				type: 'bar',
				data: planEndData,
				itemStyle: { color: '#67C23A' },
				barWidth: '35%',
				barGap: '0%',
				label: {
					show: true,
					position: 'top',
					fontSize: 10,
					color: '#333',
					fontWeight: 'bold',
				},
			},
			// 实际完工 - 柱状图
			{
				name: '实际完工',
				type: 'bar',
				data: actualEndData,
				itemStyle: { color: '#F56C6C' },
				barWidth: '35%',
				barGap: '0%',
				label: {
					show: true,
					position: 'top',
					fontSize: 10,
					color: '#333',
					fontWeight: 'bold',
					formatter: function (params: any) {
						return params.value === 0 || params.value === null ? '' : String(params.value);
					},
				},
			},
			// 计划完工 - 折线图（顺滑）
			{
				name: '计划完工(线)',
				type: 'line',
				data: planEndData,
				itemStyle: { color: '#67C23A' },
				lineStyle: { width: 2 },
				symbol: 'circle',
				symbolSize: 4,
				smooth: false,
				showInLegend: false,
			},
			// 实际完工 - 折线图（顺滑）
			{
				name: '实际完工(线)',
				type: 'line',
				data: actualEndData,
				itemStyle: { color: '#F56C6C' },
				lineStyle: { width: 2 },
				symbol: 'diamond',
				symbolSize: 4,
				smooth: false,
				connectNulls: false,
				showInLegend: false,
			},
			// 时间进度线 - 从0到最终计划完工数的斜线
			{
				name: '时间进度线',
				type: 'line',
				data: timelineData,
				itemStyle: { color: '#909399' },
				lineStyle: {
					width: 2,
					type: 'dashed',
					color: '#909399',
				},
				symbol: 'none',
				showInLegend: true,
				tooltip: {
					show: false, // 禁用时间进度线的tooltip显示
				},
			},
		];

		titleText = `${props.areaName} - 完工情况分析`;
		legendData = ['计划完工', '实际完工', '时间进度线'];
	}

	const option = {
		title: {
			text: titleText,
			left: 'center',
			textStyle: {
				fontSize: 16,
				fontWeight: 'bold',
				color: '#303133',
			},
		},
		tooltip: {
			show: true,
			trigger: 'axis',
			triggerOn: 'mousemove|click',
			confine: true,
			appendToBody: true,
			position: function (point: number[], params: any, dom: any, rect: any, size: any) {
				// 自动调整tooltip位置，避免超出容器范围
				var x = point[0];
				var y = point[1];
				var boxWidth = size.contentSize[0];
				var boxHeight = size.contentSize[1];
				var posX = x + 10;
				var posY = y + 10;

				// 如果tooltip会超出右边界，则显示在鼠标左侧
				if (posX + boxWidth > size.viewSize[0]) {
					posX = x - boxWidth - 10;
				}

				// 如果tooltip会超出下边界，则显示在鼠标上方
				if (posY + boxHeight > size.viewSize[1]) {
					posY = y - boxHeight - 10;
				}

				return [posX, posY];
			},
			axisPointer: {
				type: 'cross',
				animation: true,
				label: {
					backgroundColor: '#6a7985',
				},
			},
			formatter: function (params: any[]) {
				// 安全检查：确保params存在且不为空
				if (!params || params.length === 0) {
					return '暂无数据';
				}

				// 安全获取坐标轴值
				const axisValue = params[0]?.axisValue || params[0]?.name || '未知日期';
				let tooltipText = `<strong>${axisValue}</strong><br/>`;

				// 按照系列顺序显示，确保柱状图数据（计划数据）优先显示
				const sortedParams = params.sort((a, b) => {
					// 柱状图（计划数据）排在前面，折线图（实际数据）排在后面
					if (a.seriesType === 'bar' && b.seriesType === 'line') return -1;
					if (a.seriesType === 'line' && b.seriesType === 'bar') return 1;
					return 0;
				});

				sortedParams.forEach((param) => {
					// 安全获取参数值
					const seriesName = param.seriesName || '未知系列';
					const marker = param.marker || '●';
					// 显示所有数据，null/undefined显示为'-'，0显示为'0'
					let value;
					if (param.value === null || param.value === undefined) {
						value = '-';
					} else if (param.value === 0) {
						value = '0';
					} else {
						value = param.value.toString();
					}
					tooltipText += `${marker}${seriesName}: ${value}<br/>`;
				});
				return tooltipText;
			},
		},
		legend: {
			bottom: 5,
			data: legendData,
			textStyle: { fontSize: 12 },
		},
		grid: {
			left: '3%',
			right: '4%',
			bottom: '15%',
			top: '10%',
			containLabel: true,
		},
		xAxis: {
			type: 'category',
			data: dates,
			axisLabel: { fontSize: 10, rotate: 45 },
		},
		yAxis: {
			type: 'value',
			axisLabel: { fontSize: 10 },
		},
		series: series,
	};

	// 使用安全的渲染函数
	try {
		renderChart(option);
	} catch (error) {
		console.error('Failed to render chart with option:', error, option);
		return;
	}

	// 添加今日标记线
	const todayIndex = dates.findIndex((date) => {
		const today = new Date();
		const todayStr = `${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
		return date === todayStr;
	});

	if (todayIndex !== -1) {
		// 为第一个系列（计划完工）添加今日标记线
		const seriesWithMarkLine = [...series];
		seriesWithMarkLine[0] = {
			...seriesWithMarkLine[0],
			markLine: {
				data: [
					{
						xAxis: todayIndex,
						lineStyle: {
							color: '#F56C6C',
							width: 2,
							type: 'solid',
						},
						label: {
							formatter: '今日',
							position: 'middle',
							color: '#F56C6C',
							fontSize: 12,
							fontWeight: 'bold',
							backgroundColor: 'rgba(255, 255, 255, 0.8)',
							padding: [2, 4],
							borderRadius: 3,
						},
					},
				],
				symbol: 'none',
				silent: false,
			},
		};

		const updatedOption = {
			...option,
			series: seriesWithMarkLine,
		};
		renderChart(updatedOption);
	}
};

const resize = () => {
	if (props.showSplitLayout) {
		if (startChart) startChart.resize();
		if (endChart) endChart.resize();
	} else {
		if (chart) chart.resize();
	}
};

// 监听数据变化 - 添加防抖和错误处理
watch(
	() => props.chartData,
	() => {
		// 防抖处理，避免频繁重渲染
		clearTimeout(debounceTimer);
		debounceTimer = setTimeout(async () => {
			try {
				await nextTick();
				await option();
			} catch (error) {
				console.error('Error updating chart on data change:', error);
			}
		}, 100);
	},
	{ deep: true }
);

// 防抖定时器
let debounceTimer: NodeJS.Timeout | null = null;

// 监听区域名称变化
watch(
	() => props.areaName,
	() => {
		nextTick(async () => {
			await option();
		});
	}
);

// 监听展示模式变化
watch(
	() => props.showSplitLayout,
	() => {
		nextTick(async () => {
			await option();
		});
	}
);

onMounted(() => {
	nextTick(async () => {
		await option();
	});
});

onBeforeUnmount(() => {
	// 清理防抖定时器
	if (debounceTimer) {
		clearTimeout(debounceTimer);
		debounceTimer = null;
	}

	// 安全清理图表实例
	try {
		if (chart && !chart.isDisposed()) {
			chart.dispose();
		}
		chart = null;
	} catch (error) {
		console.warn('Error disposing main chart:', error);
	}

	try {
		if (startChart && !startChart.isDisposed()) {
			startChart.dispose();
		}
		startChart = null;
	} catch (error) {
		console.warn('Error disposing start chart:', error);
	}

	try {
		if (endChart && !endChart.isDisposed()) {
			endChart.dispose();
		}
		endChart = null;
	} catch (error) {
		console.warn('Error disposing end chart:', error);
	}
});

defineExpose({
	resize,
});
</script>

<style lang="scss" scoped>
.combined-chart-wrapper {
	width: 100%;
	height: 100%;

	.single-layout {
		width: 100%;
		height: 100%;

		.combined-chart-container {
			width: 100%;
			height: 100%;
		}
	}

	.split-layout {
		width: 100%;
		height: 100%;
		display: flex;
		gap: 10px;

		.chart-half {
			flex: 1;
			height: 100%;
			border: 1px solid var(--el-border-color-light);
			border-radius: 4px;
			padding: 10px;
			background: var(--el-bg-color);

			.chart-title {
				font-size: 14px;
				font-weight: 600;
				color: var(--el-text-color-primary);
				text-align: center;
				margin-bottom: 10px;
				padding-bottom: 8px;
				border-bottom: 1px solid var(--el-border-color-lighter);
			}

			.chart-container {
				width: 100%;
				height: calc(100% - 35px);
			}
		}

		.left-chart {
			border-color: #409eff;

			.chart-title {
				color: #409eff;
				border-bottom-color: #409eff;
			}
		}

		.right-chart {
			border-color: #e6a23c;

			.chart-title {
				color: #e6a23c;
				border-bottom-color: #e6a23c;
			}
		}
	}

	// 移动端适配
	@media (max-width: 768px) {
		.split-layout {
			flex-direction: column;
			height: auto;

			.chart-half {
				height: 300px;
			}
		}
	}
}
</style>
